package com.eliauk.demo.controller;


import com.alibaba.excel.EasyExcel;
import com.eliauk.demo.entity.User;
import com.eliauk.demo.service.IUserService;
import com.eliauk.demo.service.impl.UserServiceImpl;
import com.eliauk.demo.utils.excel.converter.DateConverter;
import com.eliauk.demo.utils.excel.listener.UserListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author ${author}
 * @since 2023-10-09
 */
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private IUserService userService;

    @PostMapping("/import")
    public String importData(MultipartFile file) throws IOException {
        InputStream in  = file.getInputStream();
        EasyExcel.read(in, User.class,new UserListener(new UserServiceImpl()))
                .sheet()
                .registerConverter(new DateConverter())
                .doRead();
        return "success";
    }

    @GetMapping("/export")
    public void exportData(HttpServletResponse response) throws IOException {
        List<User> userData = userService.list();
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), User.class)
                .sheet("模板")
                .registerConverter(new DateConverter())
                .doWrite(userData);
    }
}

